package main

import (
	"context"
	"errors"
	"flag"
	"os"
	"time"

	// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
	// to ensure that exec-entrypoint and run can make use of them.
	"github.com/Shopify/sarama"
	"github.com/go-redis/redis/v8"
	_ "k8s.io/client-go/plugin/pkg/client/auth"

	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/healthz"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"

	//+kubebuilder:scaffold:imports
	rediscommand "dataflow-operator/command/redis_command"
	"dataflow-operator/controllers"
	"dataflow-operator/k8s"
	kafkareport "dataflow-operator/report/kafka_report"
)

var (
	setupLog = ctrl.Log.WithName("setup")
)

func main() {
	//kafka reporter 配置
	flag.StringVar(&kafkareport.Config.Brokers, "kafka-brokers", "", "kafka brokers to send App status")
	flag.StringVar(&kafkareport.Config.Topic, "kafka-topic", "", "kafka topic to send App status")
	//redis commander 配置
	flag.StringVar(&rediscommand.Config.Url, "redis-url", "", "redis url")
	flag.IntVar(&rediscommand.Config.Database, "redis-db", 0, "redis db")
	flag.StringVar(&rediscommand.Config.Password, "redis-password", "", "redis password")
	flag.StringVar(&rediscommand.Partition, "partition", "", "dataflow partiton")

	//k8s 配置
	var metricsAddr string
	var enableLeaderElection bool
	var probeAddr string
	var namespace string
	flag.StringVar(&namespace, "namespace", "", "The namespace to operate.")
	flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
	flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
	flag.BoolVar(&enableLeaderElection, "leader-elect", false,
		"Enable leader election for controller manager. "+
			"Enabling this will ensure there is only one active controller manager.")
	opts := zap.Options{
		Development: true,
	}
	opts.BindFlags(flag.CommandLine)
	flag.Parse()

	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	// start KafkaReporter
	if kafkareport.Config.Brokers != "" && kafkareport.Config.Topic != "" {
		config := sarama.NewConfig()
		config.ClientID = "dataflow-operator"
		config.Producer.Timeout = 5 * time.Second
		config.Producer.Return.Successes = true
		kReporter := kafkareport.KafkaReporter{
			KafkaProducerConfig: config,
			Factory:             k8s.GetKubectlFactory(),
			Logger:              setupLog.WithName("reporter"),
		}
		go kReporter.Start(ctx)
	}

	// start redis commander
	if rediscommand.Config.Url != "" && rediscommand.Partition != "" {
		rc := rediscommand.RedisCommander{
			RedisClient: redis.NewClient(&redis.Options{
				Addr:     rediscommand.Config.Url,
				Password: rediscommand.Config.Password,
				DB:       rediscommand.Config.Database,
			}),
			Logger: setupLog.WithName("commander"),
		}
		go rc.Start(ctx)
	}

	//start k8s operator
	ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

	if namespace == "" {
		flag.Usage()
		setupLog.Error(errors.New(""), "namespace can't be nil")
		os.Exit(-1)
	}
	mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
		MetricsBindAddress:     metricsAddr,
		Port:                   9443,
		HealthProbeBindAddress: probeAddr,
		LeaderElection:         enableLeaderElection,
		LeaderElectionID:       "25ca1eb8.online.daq.ihep",
	})
	if err != nil {
		setupLog.Error(err, "unable to start manager")
		os.Exit(1)
	}

	if err = (&controllers.ConfigReconciler{
		Client: mgr.GetClient(),
		Logger: ctrl.Log.WithName("ConfigReconciler"),
	}).SetupWithManager(mgr); err != nil {
		setupLog.Error(err, "unable to create controller", "controller", "Pod")
		os.Exit(1)
	}

	//+kubebuilder:scaffold:builder

	if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
		setupLog.Error(err, "unable to set up health check")
		os.Exit(1)
	}
	if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
		setupLog.Error(err, "unable to set up ready check")
		os.Exit(1)
	}

	setupLog.Info("starting manager")
	if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
		setupLog.Error(err, "problem running manager")
		os.Exit(1)
	}
}
